package itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import itheima.reggie.common.CustomException;
import itheima.reggie.common.R;
import itheima.reggie.entity.Category;
import itheima.reggie.service.CategoryService;
import itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
    @PostMapping
    public R<String> saveCategory(@RequestBody  Category category){
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        //公共字段自动装配
        //调用service保存数据到数据库
        categoryService.save(category);
        return R.success("新增分类成功!");
    }

    //分页查询 菜品
    @GetMapping("/page")
    public R<Page> queryInfo(int page,int pageSize){
        log.info("page={},pageSize={}",page,pageSize);
        //构造分页构造器
        Page pageInfo=new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper();
        //添加排序条件,根据sort
        queryWrapper.orderByAsc(Category::getSort);
        //执行查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }
    //根据id删除分类
    @DeleteMapping("")
    public R<String> deleteSort(Long ids){
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        try {
            categoryService.remove(ids);
        }catch (CustomException e){
            return R.error(e.getMessage());
        }
       return R.success("1");

    }
    //修改分类
    @PutMapping("")
    public R<String> editCategory(@RequestBody Category category){
        if (BaseContext.getCurrentId()!=1){return R.error("当前用户只能查看！！");}
        log.info("修改分类信息：{}",category);

        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }
    //菜品类型
    @GetMapping("/list")
    public R<List<Category>> queryList(Category category){
        LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper();
        //添加条件
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }

}

